const express=require('express');
const request=require('request');
const  { mysqls } = require('../../utils/mysql');
const  { wxApp,getOpenid } = require('../../utils/file');

//返回格式
var response = {
    code : 0,
    msg : '',
    data : null
};

var route = express.Router();

route.get('/getOpenid',(req,res)=>{
    console.log(req.query);
    request(`https://api.weixin.qq.com/sns/jscode2session?appid=${wxApp.appID}&secret=${wxApp.AppSecret}&js_code=${req.query.code}&grant_type=authorization_code`,(err,res,body)=>{
        body = JSON.parse(body);
        console.log(body.openid);
    })
})
//登陆
route.post('/login',async(req,res)=>{
    var {nickName,gender,language,city,province,avatarUrl,code} = req.body;
    if(!code){
        response.code = 1;
        response.msg = '缺少code'
        res.json(response);
    }
    var openid = await getOpenid(code);
    var data = await mysqls(`select*from user where openid = '${openid}'`,res)
    if(data[0]){
        //已有该用户
        response.data = data[0];
        res.json(response)
    }else{
        //没有该用户
        let confirm = await mysqls(`insert into user (username,sex,headimgurl,city,provice,openid) values ('${nickName}',${gender},'${avatarUrl}','${city}','${province}','${openid}')`,res);
        response.data = {username:nickName,sex:gender,headimgurl:avatarUrl,city:city,provice:province,openid:openid};
        res.json(response)
    }

})

//需求消息发布
route.post('/setDemand',async(req,res)=>{
    var {words, picture,record,location,userId} = req.body;
    var time = (new Date()).getTime();
    let mysql = `insert into demand (words,picture,record,location,userId,time) values (${words?words+'':null},${picture?picture+'':null},${record?record+'':null},${location?location+'':null},${userId?userId+'':null},${time})`
    let confirm = await mysqls(mysql,res)
    res.json(response)
})









module.exports = route;

